import { defineStore } from 'pinia'
import api from '../api'

export const useFolderStore = defineStore('folders', {
  state: () => ({
    tree: [],
    flat: [],
    loading: false,
    error: ''
  }),
  actions: {
    async load() {
      this.loading = true; this.error = ''
      try {
        const [treeRes, listRes] = await Promise.all([
          api.get('/api/folders/tree'),
          api.get('/api/folders')
        ])
        this.tree = treeRes.data
        this.flat = listRes.data
      } catch (e) {
        this.error = e?.response?.data?.detail || '加载目录失败'
      } finally { this.loading = false }
    },
    async create(name, parent_id = null) {
      await api.post('/api/folders', { name, parent_id })
      await this.load()
    },
    async rename(id, name, parent_id) {
      await api.put(`/api/folders/${id}`, { name, parent_id })
      await this.load()
    },
    async remove(id) {
      await api.delete(`/api/folders/${id}`)
      await this.load()
    },
    async move(id, parent_id) {
      let item = this.flat.find(f => f.id === id)
      if (!item) { await this.load(); item = this.flat.find(f => f.id === id) }
      const name = item ? item.name : ''
      await api.put(`/api/folders/${id}`, { name, parent_id })
      await this.load()
    },
    async reorder(id, { parent_id = null, before_id = null, after_id = null }) {
      await api.patch(`/api/folders/reorder/${id}`, { parent_id, before_id, after_id })
      await this.load()
    }
  }
})
